package Array;

import java.util.*;

public class item347 {
    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i <nums.length ; i++) {
            if(map.containsKey(nums[i]))
            {
                Integer tmp = map.get(nums[i]);
                tmp= tmp+1;
                map.put(nums[i],tmp);
            }else
                map.put(nums[i],1);
        }
        int []res = new int[k];
        PriorityQueue<Map.Entry<Integer,Integer>> pq = new PriorityQueue<>(new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o1.getValue()-o2.getValue();
            }
        });
        Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
        for(Map.Entry entry :entries)
        {
            pq.add(entry);
            if(pq.size()>k)
                pq.poll();
        }
        int i = 0;
        while (!pq.isEmpty())
        {
           res[i]=pq.poll().getKey();
           i++;
        }

        return res;
    }
}
